package org.zjx.action.game.inventor;

import org.zjx.analysis.window.InventorAnalysis;
import org.zjx.analysis.inventor.InventorHandOffAnalysis;
import org.zjx.action.game.AbstractWindowAction;
import org.zjx.core.IWindow;
import org.zjx.enums.prop.SlotType;
import org.zjx.model.prop.ItemInstance;
import org.zjx.state.ItemState;

import java.awt.*;
import java.util.List;

public class InventorHandOffAction extends AbstractWindowAction {
    private final InventorAnalysis inventorAnalysis;
    private InventorHandOffAnalysis inventorHandOffAnalysis;

    public InventorHandOffAction(IWindow targetWindow, InventorAnalysis inventorAnalysis) {
        super(targetWindow);
        this.inventorAnalysis = inventorAnalysis;
    }

    @Override
    protected void doExecute() throws Exception {
        analysis();
        while (!inventorHandOffAnalysis.isOpened()) {
            open();
        }
        Rectangle sureButton = inventorHandOffAnalysis.conversion(inventorHandOffAnalysis.windowArea, inventorHandOffAnalysis.getSureArea());
        while (inventorHandOffAnalysis.isOpened()) {
            click(sureButton);
            analysis();
        }
        switchInventory();
        delay(500);
    }

    @Override
    public void open() {
        if (!inventorAnalysis.isOpened()) throw new IllegalArgumentException("道具栏未打开!!!");
        analysis();
        mouseAloofWindow(inventorHandOffAnalysis.windowArea == null? inventorHandOffAnalysis.getOriginBounds(): inventorHandOffAnalysis.windowArea);
        if (inventorHandOffAnalysis.isOpened()) return;
        Rectangle handOffButton = inventorAnalysis.conversion(inventorAnalysis.windowArea, inventorAnalysis.imageMap.get("行囊切换按钮").getRectangle());
        click(handOffButton);
    }

    /**
     * 切换背包
     */
    private void switchInventory() {
        ItemState itemState = stateManager.getState(ItemState.class);
        List<ItemInstance> instances = itemState.getItemsByType(SlotType.INVENTORY);
        itemState.getItems().put(SlotType.INVENTORY, itemState.getItemsByType(SlotType.EXTENDED_INVENTORY));
        itemState.getItems().put(SlotType.EXTENDED_INVENTORY, instances);
    }

    @Override
    public void close() {

    }

    @Override
    public void reSetWindow() {

    }

    @Override
    public void mouseAloofWindow(Rectangle rect) {
        if (inventorHandOffAnalysis.mouseInRect(rect)) {
            Point safePoint = inventorHandOffAnalysis.findLargestRemainingAreaCenter(rect);
            move(safePoint);
        }
    }

    private void analysis() {
        inventorHandOffAnalysis = new InventorHandOffAnalysis(targetWindow, stateManager.getGameState().getScreenshot());
    }
}
